package com.example.sms.service.impl;

import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.example.sms.bo.sms.ShortMessage;
import com.example.sms.service.SMSServiceI;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class SMSServiceImpl implements SMSServiceI {
    @Autowired
    SendSmsRequest.Builder sendSmsRequestBuilder;
    @Autowired
    AsyncClient smsAsyncSendClient;
    //这里就简单的校验一下发送消息后返回的状态码
    private boolean checkSendCode(String code){
        return code.equals("OK");
    }
    @Override
    public boolean sendSms(ShortMessage message) {
        boolean sendState=true;
        SendSmsRequest sendSmsRequest = sendSmsRequestBuilder.phoneNumbers(message.getAcceptPhoneNumber())
                .outId(message.getOutId())
                .templateParam(message.getCode()).build();
        CompletableFuture<SendSmsResponse> response = smsAsyncSendClient.sendSms(sendSmsRequest);
        try {
            SendSmsResponse sendSmsResponse = response.get();
            String code = sendSmsResponse.getBody().getCode();
            if(!checkSendCode(code)){
                sendState=false;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return sendState;
    }
}
